<template>
  <TablePage
    v-show="!isProjectSetting || show"
    :id="props.isProjectSetting ? 'projectSetting-gateway' : ''"
    :class="{ 'p-0': isProjectSetting }"
    class="relative"
  >
    <template #top>
      <SearchForm
        title="网关"
        :title-size-class="isProjectSetting ? 'text-xl' : void 0"
        add-btn-text="新增网关"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        :add-btn-disabled="loadingProject"
        :keyword-search-data="keywordSearchData"
        :select-data="selectData"
        @add="showCreateModal"
        @search="handleSearch"
      ></SearchForm>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :pagination="pagination" :loading="tableLoading">
      <template #bodyCell="{ record, column }">
        <div v-if="column.dataIndex === 'oper'">
          <PermissionBtn
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleSetPoint(record)"
          >
            设置点位
          </PermissionBtn>
          <PermissionBtn
            class="mx-2"
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
          >
            编辑
          </PermissionBtn>
          <PermissionBtn
            :btn-props="{ type: 'link', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleDel(record)"
          >
            删除
          </PermissionBtn>
        </div>
        <div v-else-if="column.dataIndex === 'gatewayName'">
          <a class="inline-block" href="javascript:void(0)" @click="showDetail(record)">
            <EllipsisText :text="record.gatewayName" :max-len="20" />
          </a>
        </div>
        <div v-else-if="column.dataIndex === 'isOnline'">
          <span :class="[record.isOnline ? 'text-color-success' : 'text-color-disabled']">
            {{ record.isOnline ? "在线" : "离线" }}
          </span>
        </div>
      </template>
    </SlTable>
    <CURDDialog
      id-key="gatewayId"
      create-title="新增网关信息"
      update-title="编辑网关信息"
      check-title="查看网关信息"
      :model="gModel"
      :model-form-setting="gFormSetting"
      delete-message="您确定删除该网关吗？"
      :curd="curd"
      :show-options="showOptions"
      :reload-table="reloadTable"
      :table-data="tableData"
      :drawer-container-selector="isProjectSetting ? '#project-detail-content' : void 0"
      :oper-data="operData"
      force-column
      :next-add-btn-options="{ text: '确定并设置点位', handler: okAndSetPoint }"
      @open="open"
    />
    <SetPointModal
      :options="setPointOptions"
      :title="setPointTitle"
      :get-container="getContainer"
      :is-project-setting="isProjectSetting"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref, h, watch } from "vue";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { useCURD } from "/@/hooks/useCURD";
import { Api } from "/@/api/aiot/gateway";
import { Api as projectApi } from "/@/api/aiot/projectManage";
import { GatewayItem, GatewayPointItem, GatewayTypeItem } from "/@/api/aiot/gateway/models";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  OperItem,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { message, SelectProps, TableColumnProps } from "ant-design-vue";
import type { SelectItem } from "/@/types/components";
import type { CustomAttributesItem, ProjectItem } from "/@/api/aiot/projectManage/models";
import type { SelectOptionItem } from "/@/types/antd";
import { PatternKey } from "/@/utils/verify";
import GatewayTypeSelect from "./GatewayTypeSelect.vue";
import SetPointModal from "./SetPointModal.vue";
import { isEmpty } from "lodash-es";
import CustomAttr from "/@/components/CustomAttr.vue";

const props = defineProps<{
  isProjectSetting?: boolean;
  projectId?: string;
  show?: boolean;
}>();

/**
 * search
 */
const selectData = ref<SelectItem[]>(
  props.isProjectSetting
    ? []
    : [
        {
          label: "所属项目",
          value: "",
          key: "projectId",
          props: {},
          options: [],
        },
        // {
        //   label: "网关状态",
        //   value: "",
        //   key: "isOnline",
        //   options: [
        //     { label: "全部", value: "" },
        //     { label: "在线", value: 1 },
        //     { label: "离线", value: 0 },
        //   ],
        // },
      ]
);
const {
  tableData: projectData,
  reloadTable: reloadProjectData,
  tableLoading: loadingProject,
} = useCURD<ProjectItem>({
  getPageUrl: projectApi.projectsPage,
  loadOnMounted: false,
  pageSize: 999,
});
onMounted(async () => {
  if (!props.isProjectSetting) {
    const projectSelPorps = selectData.value[0].props;
    if (projectSelPorps) {
      projectSelPorps.loading = true;
      await reloadProjectData();
      projectSelPorps.loading = false;
      let options: SelectOptionItem[] = [
        {
          label: "全部项目",
          value: "",
        },
      ];
      options = options.concat(
        projectData.value.map((el) => ({
          label: el.projectName,
          value: el.projectId,
        }))
      );
      selectData.value[0].options = options;
    }
  }
});
const keywordSearchData = [{ key: "searchText", label: "网关名称/网关编号" }];
function handleSearch(model) {
  reloadTable({
    model,
  });
}
/**
 * table
 */
const { tableData, tableLoading, reloadTable, curd, pagination } = useCURD<Partial<GatewayItem>>({
  getPageUrl: Api.gatewayPage,
  createUrl: Api.addGateway,
  updateUrl: Api.updateGateway,
  deleteUrl: Api.deleteGateways,
  loadOnMounted: !props.isProjectSetting,
});
if (props.isProjectSetting) {
  //项目设置中 第一次显示才加载数据
  let firstShow = true;
  watch(
    () => props.show,
    (v) => {
      if (v) {
        if (firstShow) {
          firstShow = false;
          reloadTable({
            model: {
              projectId: props.projectId,
            },
          });
        }
      } else {
        setPointOptions.value = void 0;
      }
    }
  );
}
const columns = ref<TableColumnProps<GatewayItem>[]>([
  {
    title: "网关名称",
    dataIndex: "gatewayName",
  },
  {
    title: "所属项目",
    dataIndex: "projectName",
  },
  {
    title: "网关编号",
    dataIndex: "gatewayCode",
  },
  {
    title: "网关唯一标识",
    dataIndex: "gatewaySerialNumber",
  },
  {
    title: "网关类型",
    dataIndex: "gatewayTypeName",
  },
  {
    title: "网关状态",
    dataIndex: "isOnline",
  },
  {
    title: "最近在线时间",
    dataIndex: "onlineTimeStr",
  },
  {
    title: "操作",
    dataIndex: "oper",
  },
]);
/**
 * curd modal
 */
const gModel = ref<Partial<GatewayItem>>({
  gatewayName: "",
  gatewayCode: "",
  projectId: props.projectId,
  gatewayTypeId: "",
  gatewaySerialNumber: "",
  gatewayModel: "",
  location: "",
  extend: "",
});
const { tableData: gtData, reloadTable: reloadGt } = useCURD<Partial<GatewayTypeItem>>({
  getPageUrl: Api.gatewayTypePage,
  loadOnMounted: false,
});
const gFormSetting = ref<FormItemData<Partial<GatewayItem>>[]>([
  {
    key: "gatewayName",
    required: true,
    label: "网关名称",
    pattern: PatternKey.name,
    max: 32,
  },
  {
    key: "gatewayCode",
    required: true,
    label: "网关编号",
    labelDes: "支持大小写字母、数字和下划线，例如：按资产编号顺序编号、按网关类型编号等",
    pattern: PatternKey.code,
    max: 64,
  },
  {
    key: "projectId",
    type: FormItemComponentType.SELECT,
    label: "所属项目",
    textKey: "label",
    valueKey: "value",
    required: true,
    async getData() {
      if (selectData.value[0]) {
        let options = selectData.value[0].options;
        if (options) {
          options = [...options];
          options.shift();
        }
        return options || [];
      } else {
        await reloadProjectData();
        return projectData.value.map((el) => ({
          label: el.projectName,
          value: el.projectId,
        }));
      }
    },
    props: {
      options: [],
      disabled: props.isProjectSetting,
    },
  },
  {
    key: "gatewayTypeId",
    label: "网关类型",
    // type: FormItemComponentType.SELECT,
    required: true,
    async getData() {
      await reloadGt();
      return gtData.value;
    },
    props: {
      disabled: false,
    },
    customComponent: h(GatewayTypeSelect),
    getText(value) {
      const result = gtData.value.find((el) => el.gatewayTypeId === value);
      return result ? (result.gatewayTypeName as string) : "--";
    },
  },
  {
    key: "gatewaySerialNumber",
    required: true,
    label: "网关唯一标识",
    labelDes: "支持大小写字母、数字和下划线",
    pattern: PatternKey.code,
    max: 64,
  },
  {
    key: "gatewayModel",
    label: "规格型号",
    max: 64,
  },
  {
    key: "location",
    label: "安装位置",
    labelDes: "建议按照“园区-建筑-楼层录入",
    max: 250,
  },
  {
    key: "extend",
    customComponent: h(CustomAttr),
    label: "",
    checkLabel: "自定义属性",
    getText(value) {
      if (!value) return "--";
      let data: CustomAttributesItem[] | null = null;
      try {
        data = JSON.parse(value);
      } catch (ex) {}
      if (data) {
        const result: string[] = [];
        data.forEach((el) => {
          result.push(`<tr><td class='text-right pr-2'>${el.customLabel}:</td> <td>${el.customValue}</td></tr>`);
        });
        return `<table>${result.join("")}</table>`;
      }
      return "--";
    },
  },
]);
const showOptions = ref<ShowCURDModalOptions>();
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function handleDel(record: GatewayItem) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
const operData: OperItem<GatewayItem>[] = [
  {
    label: "编辑",
    handler: showUpdateModal,
    operType: OperPermissionType.MANAGE,
  },
  {
    label: "删除",
    type: "primary",
    danger: true,
    handler: handleDel,
    operType: OperPermissionType.MANAGE,
  },
];
function showDetail(record) {
  showOptions.value = { action: CURDAction.CHECK, record };
}
function okAndSetPoint(data: Partial<GatewayItem>) {
  showOptions.value = void 0;
  handleSetPoint(data);
}
/**
 * 编辑网关
 */
const { tableData: gpData, reloadTable: reloadGp } = useCURD<GatewayPointItem>({
  getPageUrl: Api.gatewayDataPointsPage,
  loadOnMounted: false,
  pageSize: 1,
});
//打开编辑前 需判断网关有没有点位，且有没有绑定过设备，其中一样有都不能编辑网关类型
let gtDisabled = false;
async function showUpdateModal(record: GatewayItem) {
  tableLoading.value = true;
  await reloadGp({
    model: {
      gatewayId: record.gatewayId,
    },
  });
  tableLoading.value = false;
  if (gpData.value.length > 0) {
    gtDisabled = true;
  } else {
    gtDisabled = false;
  }
  showOptions.value = { record, action: CURDAction.UPDATE };
}
function open({ action, formItemData }: CURDModalEvent) {
  const target = formItemData.find((item) => item.key === "gatewayTypeId");
  if (target && target.props) {
    if (action === CURDAction.UPDATE) {
      target.props.disabled = gtDisabled;
    } else {
      target.props.disabled = false;
    }
  }
}
/**
 * table oper
 */
const setPointOptions = ref<{ gatewayTypeId: string; gatewayId: string }>();
const setPointTitle = ref("");
function handleSetPoint(record: Partial<GatewayItem>) {
  // const codePrefix = isEmpty(record.gatewayCode) ? "" : `(${record.gatewayCode})`;
  setPointTitle.value = `设置点位(${record.gatewayName})`;
  setPointOptions.value = {
    gatewayTypeId: record.gatewayTypeId as string,
    gatewayId: record.gatewayId as string,
  };
}
function getContainer() {
  return props.isProjectSetting
    ? (document.getElementById("projectSetting-gateway") as HTMLElement)
    : (document.getElementById("home-content") as HTMLElement);
}
</script>
